package com.xmbandu.app.activity.guide;

import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.android.tu.loadingdialog.LoadingDailog;
import com.everobo.robot.sdk.ReadBookInterface;
import com.everobo.robot.sdk.interfac.RestigerInterfaceCallBack;
import com.xmbandu.app.R;
import com.xmbandu.app.activity.H5PayActivity;
import com.xmbandu.app.activity.LoginActivity;
import com.xmbandu.app.base.BaseActivity;
import com.xmbandu.app.base.SspConfig;
import com.xmbandu.app.home.MainActivity;
import com.xmbandu.app.qrcode.activity.CaptureActivity;
import com.xmbandu.app.utils.CommonUtils;
import com.xmbandu.app.utils.SspPrefUtils;
import com.xmbandu.app.view.RxDialogSureCancel;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author wmq
 * @date 2019-05-15
 * @description
 */
public class SplashThreeActvity extends BaseActivity {
    ConstraintLayout next;
    String url = "https://item.taobao.com/item.htm?spm=a1z10.1-c-s.w4004-21619375264.2.52d2947beRai80&id=593322784139";
    int tag = 0;
    @Override
    public int getLayoutId() {
        return R.layout.activity_splash_three;
    }

    @Override
    public void initViews() {
        tag = getIntent().getIntExtra("tag",0);
        next = findViewById(R.id.img_next);

    }

    @Override
    public void initListener() {
        setOnClick(next);

    }

    @Override
    public void initData() {

    }

    @Override
    public void processClick(View v) {
        if(v.getId()==R.id.img_next){
            if(CommonUtils.isClickable()){
                if(tag==1){
                    if(TextUtils.isEmpty(SspPrefUtils.getString("deviceid",""))){
                        Intent intent = new Intent(SplashThreeActvity.this, CaptureActivity.class);
                        startActivityForResult(intent, SspConfig.REQ_QR_CODE);
                    }else {
                        ReadBookInterface.register(SspPrefUtils.getString("deviceid",""), new RestigerInterfaceCallBack() {
                            @Override
                            public void succes(String s) {
                                SplashThreeActvity.this.finish();
                                ReadBookInterface.startRead(SplashThreeActvity.this);
//                        com.everobo.robot.phone.ui.MainActivity.gotoThis(MainActivity.this);
                            }

                            @Override
                            public void fail(Object o) {
                                Log.e("TAGGG", "登陆失败");
                            }
                        });
                    }


                } else {
                    ReadBookInterface.register(SspPrefUtils.getString("deviceid",""), new RestigerInterfaceCallBack() {
                        @Override
                        public void succes(String s) {
                             SplashThreeActvity.this.finish();
                             ReadBookInterface.startRead(SplashThreeActvity.this);
//                        com.everobo.robot.phone.ui.MainActivity.gotoThis(MainActivity.this);
                    }

                        @Override
                        public void fail(Object o) {
                        Log.e("TAGGG", "登陆失败");
                    }
                    });
                 }


            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == SspConfig.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(SspConfig.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
//            tvResult.setText(scanResult);
//            getDeviceId(scanResult);
            Log.e("SplashThreeActvity", "onActivityResult: "+scanResult );
            bindDeviceId(scanResult);
        }
    }
    /**
     * 绑定deviceid
     * @param scanResult
     */
    private void bindDeviceId(String scanResult) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .addHeader("XX-Api-Version", "v1")
                .addHeader("XX-Token", SspPrefUtils.getString("token",""))
                .url(scanResult+"&source=app")
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("SplashThreeActvity", "onFailure: "+call.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.e("MainActivity", "onResponse: " + response.body().string());
                try {
                    JSONObject object = new JSONObject(response.body().string());
                    int code = object.getInt("code");
                    switch (code){
                        case 1:
                            JSONObject data  = object.getJSONObject("data");
                            String deviveid = data.getString("deviceid");
                            SspPrefUtils.setString("deviceid",deviveid);
                            final LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(SplashThreeActvity.this)
                                    .setMessage("加载中...")
                                    .setCancelable(true)
                                    .setCancelOutside(true);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    final LoadingDailog dialogs=loadBuilder.create();
                                    dialogs.show();

                                        ReadBookInterface.register(SspPrefUtils.getString("deviceid",""), new RestigerInterfaceCallBack() {
                                            @Override
                                            public void succes(String s) {
                                                dialogs.dismiss();
                                                SplashThreeActvity.this.finish();
                                                ReadBookInterface.startRead(SplashThreeActvity.this);
                                            }

                                            @Override
                                            public void fail(Object o) {
                                                dialogs.dismiss();
                                                Log.e("TAGGG", "登陆失败");
                                            }
                                        });
                                    }

                            });



                            break;
                        case 10001:
                            Intent intent = new Intent(SplashThreeActvity.this, LoginActivity.class);
                            startActivity(intent);
                            finish();
                            break;
                        case 0:
                            if(object.getString("msg").equals("该设备已被他人绑定")){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        DiyDialog("该设备已被他人绑定");//提示购买

                                    }
                                });
                            }else if(object.getString("msg").equals("您的账号已绑定其他设备")){//提示用户换个账号
                                Intent login = new Intent(SplashThreeActvity.this,LoginActivity.class);
                                startActivity(login);
                                finish();
                            }else {
                                Toast.makeText(SplashThreeActvity.this,object.getString("msg"),Toast.LENGTH_SHORT).show();
                            }
                            break;


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }


    private void DiyDialog(String msg){
        //提示弹窗
        final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(this);
        rxDialogSureCancel.getTitleView().setBackgroundResource(R.mipmap.logo);
        rxDialogSureCancel.getContentView().setText(msg+"是否购买新设备？");
        rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(SspPrefUtils.getString("weburl",""))){
                    H5PayActivity.intoSspCommonWeb(SplashThreeActvity.this,url);
                }
                H5PayActivity.intoSspCommonWeb(SplashThreeActvity.this,SspPrefUtils.getString("weburl",""));
//                if (AppInstallUtils.isTaoBaoAvailable(MainActivity.this)) {
//                    //跳转淘宝店铺
//                    String url = "taobao://shop.m.taobao.com/shop/shop_index.htm?shop_id=268113955";
//                    Intent intent = new Intent();
//                    intent.setAction("Android.intent.action.VIEW");
//                    Uri uri = Uri.parse(url); // 商品地址
//                    intent.setData(uri);
//                    intent.setClassName("com.taobao.taobao","com.taobao.android.shop.activity.ShopHomePageActivity");
//                    startActivity(intent);
//                } else {
//                    Toast.makeText(MainActivity.this, "请下载淘宝app再进行商品的购买!", Toast.LENGTH_SHORT).show();
//                }
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
            }
        });

        rxDialogSureCancel.show();
    }
}
